package cn.tongdun.context;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;

import java.io.InputStream;
import java.util.Iterator;

import static cn.tongdun.atreus.common.log.DesensitizationUtil.LOG_OPEN_KEY;

/**
 * @author wangze
 * @date 2021-10-24 15:59.
 **/
public class JnLoggerContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>,Ordered {
	private Logger logger = LoggerFactory.getLogger(JnLoggerContextInitializer.class);

	public JnLoggerContextInitializer() {
	}

	@Override
	public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
		ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
		this.initProperty(environment);
		LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("tdxmljn/tdlog.xml");
		if (inputStream == null) {
			this.logger.error("logbackConfigPath file is no exist");
		} else {
			loggerContext.reset();
			JoranConfigurator joranConfigurator = new JoranConfigurator();
			joranConfigurator.setContext(loggerContext);
			loggerContext.reset();
			try {
				joranConfigurator.doConfigure(inputStream);

			} catch (JoranException ex) {
				this.logger.error("logbackConfigPath Load logback config file error. error: {}", ex);
			}

			this.setLevels(environment, loggerContext);
			if (this.logger.isInfoEnabled()) {
				this.logger.info("JNBANK load tdlog success");
			}

		}
	}


	public void initProperty(ConfigurableEnvironment environment) {
		System.setProperty("LOG_HOME", environment.getProperty("logging.td.file.path", ".//logs"));
		System.setProperty("LOG_FILE_MAX_SIZE", environment.getProperty("logging.file.max-size", "200MB"));
		System.setProperty("LOG_FILE_MAX_HISTORY", environment.getProperty("logging.file.max-history", "7"));
		System.setProperty("LOG_FILE_TOTAL_SIZE_CAP", environment.getProperty("logging.file.total-size-cap", "2GB"));
		System.setProperty("APP_LOG_FILE", environment.getProperty("logging.app.log.file", "app"));
		System.setProperty("ERROR_LOG_FILE", environment.getProperty("logging.error.log.file", "error"));
		System.setProperty(LOG_OPEN_KEY, environment.getProperty("logging.open", "false"));

	}

	public void setLevels(ConfigurableEnvironment environment, LoggerContext loggerContext) {
		Iterator var4 = environment.getPropertySources().iterator();

		while(true) {
			PropertySource propertySource;
			do {
				if (!var4.hasNext()) {
					return;
				}

				propertySource = (PropertySource)var4.next();
			} while(!(propertySource instanceof EnumerablePropertySource));

			String[] var6 = ((EnumerablePropertySource)propertySource).getPropertyNames();
			int var7 = var6.length;

			for(int var8 = 0; var8 < var7; ++var8) {
				String property = var6[var8];
				if (property.startsWith("logging.level.")) {
					String packageName = property.substring("logging.level.".length());
					ch.qos.logback.classic.Logger logger = loggerContext.getLogger(packageName);
					logger.setLevel(Level.toLevel(environment.getProperty(property)));
				}
			}
		}
	}

	@Override
	public int getOrder() {
		return Integer.MAX_VALUE;
	}
}
